/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.flexengine.crypt;

import com.flexengine.logger.Logger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Luann R. Athayde
 * @version 1.0
 * @since 1.0
 */
public class FlexEngineHashCode {
    
    public static String getHexaHash(String srt, String algoritm) {
        return stringHexa(getHash(srt, algoritm));
    }
    
    public static byte[] getHash(String str, String algorithm) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(str.getBytes());
            return md.digest();
        } catch (NoSuchAlgorithmException e) {
            Logger.logError(FlexEngineHashCode.class.getSimpleName()+" - getHash(): "+e);
            return null;
        }
    }
    
    public static String stringHexa(byte[] bytes) {
        if( bytes==null ) {
            Logger.logError(FlexEngineHashCode.class.getSimpleName()+" - stringHexa(): [bytes] is NULL!");
            return null;
        }
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            int highPart = ((bytes[i] >> 4) & 0xf) << 4;
            int lowPart = bytes[i] & 0xf;
            if (highPart == 0) {
                s.append('0');
            }
            s.append(Integer.toHexString(highPart | lowPart));
        }
        return s.toString();
    }
    
}
